<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useServerStore } from '../stores/serverStore'
import axios from 'axios'
import type { MCPServer } from '../types'

const route = useRoute()
const router = useRouter()
const serverStore = useServerStore()

// 获取服务器ID
const serverId = computed(() => route.params.id as string)

// 获取服务器详情
const server = computed(() => 
  serverStore.servers.find(s => s.id === serverId.value)
)

// Tab切换
const activeTab = ref('url') // 默认选中URL标签页

// 添加README内容的ref
const readmeContent = ref<string | null>(null)
const readmeLoading = ref(false)
const readmeError = ref<string | null>(null)

// 如果服务器商店为空，获取数据
onMounted(async () => {
  if (serverStore.servers.length === 0) {
    await serverStore.fetchServers()
  }
  
  // 如果有Github链接，获取README内容
  if (server.value?.github) {
    await fetchReadmeContent()
  }
})

// 获取README内容
const fetchReadmeContent = async () => {
  if (!server.value?.github) return
  
  readmeLoading.value = true
  readmeError.value = null
  
  try {
    // 从GitHub URL提取用户名和仓库名
    const parts = server.value.github.split('/')
    const username = parts[parts.length - 2]
    const repo = parts[parts.length - 1]
    
    // 获取README内容
    const response = await axios.get(`https://raw.githubusercontent.com/${username}/${repo}/main/README.md`)
    readmeContent.value = response.data
  } catch (error) {
    try {
      // 尝试master分支
      const parts = server.value.github.split('/')
      const username = parts[parts.length - 2]
      const repo = parts[parts.length - 1]
      
      const response = await axios.get(`https://raw.githubusercontent.com/${username}/${repo}/master/README.md`)
      readmeContent.value = response.data
    } catch(error) {
      console.error('获取README内容失败', error)
      readmeError.value = '无法加载README内容'
    }
  } finally {
    readmeLoading.value = false
  }
}

// 返回首页
const goBack = () => {
  router.push({ name: 'home' })
}
</script>

<template>
  <div class="min-h-screen">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-lg sticky top-0 z-10">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex">
            <div class="flex-shrink-0 flex items-center">
              <h1 class="text-2xl font-bold text-gray-900 cursor-pointer" @click="goBack">
                MCP Server <span class="text-blue-600">导航</span>
              </h1>
            </div>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="page-container">
      <!-- 加载状态 -->
      <div v-if="serverStore.isLoading" class="flex justify-center my-8">
        <div class="spinner"></div>
      </div>

      <!-- 错误提示 -->
      <div v-else-if="serverStore.error" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 my-4 rounded">
        <p>{{ serverStore.error }}</p>
      </div>

      <!-- 服务器未找到 -->
      <div v-else-if="!server" class="text-center py-12">
        <div class="text-5xl mb-4">🔍</div>
        <h3 class="text-xl font-medium text-gray-900 mb-2">服务器未找到</h3>
        <p class="text-gray-600 mb-6">无法找到ID为 "{{ serverId }}" 的服务器</p>
        <button 
          @click="goBack" 
          class="btn btn-primary"
        >
          返回首页
        </button>
      </div>

      <!-- 服务器详情 -->
      <div v-else class="space-y-8">
        <!-- 返回链接 -->
        <div>
          <button 
            @click="goBack" 
            class="inline-flex items-center text-blue-600 hover:text-blue-800"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
            </svg>
            返回服务器列表
          </button>
        </div>

        <!-- 头部信息 -->
        <div class="card p-6">
          <div class="flex justify-between items-start">
            <div>
              <div class="flex items-center">
                <h1 class="text-3xl font-bold text-gray-900">{{ server!.name }}</h1>
                <span
                  :class="[
                    'ml-4',
                    'tag',
                    server!.type === 'official' ? 'tag-success' : 'tag-primary'
                  ]"
                >
                  {{ server!.type === 'official' ? '官方' : '社区' }}
                </span>
              </div>
              <p class="text-gray-500 mt-1">提供者: {{ server!.provider }}</p>
            </div>
          </div>
          
          <div class="mt-6">
            <p class="text-gray-700 text-lg">{{ server!.description }}</p>
          </div>

          <div class="mt-6 flex flex-wrap gap-2">
            <span
              v-for="tag in server!.tags"
              :key="tag"
              class="tag tag-secondary"
            >
              {{ tag }}
            </span>
          </div>
        </div>

        <!-- 详细信息 -->
        <div class="card p-6">
          <h2 class="text-xl font-bold text-gray-900 mb-4">详细信息</h2>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div v-if="server!.url">
              <h3 class="text-sm font-medium text-gray-500">URL</h3>
              <a :href="server!.url" target="_blank" class="text-blue-600 hover:text-blue-800 hover:underline">
                {{ server!.url }}
              </a>
            </div>
            
            <div v-if="server!.github">
              <h3 class="text-sm font-medium text-gray-500">GitHub</h3>
              <a :href="server!.github" target="_blank" class="text-blue-600 hover:text-blue-800 hover:underline">
                {{ server!.github }}
              </a>
            </div>
            
            <div v-if="server!.documentation">
              <h3 class="text-sm font-medium text-gray-500">文档</h3>
              <a :href="server!.documentation" target="_blank" class="text-blue-600 hover:text-blue-800 hover:underline">
                {{ server!.documentation }}
              </a>
            </div>

            <div v-if="server!.language && server!.language.length > 0">
              <h3 class="text-sm font-medium text-gray-500">支持的语言</h3>
              <div class="flex flex-wrap gap-2 mt-1">
                <span
                  v-for="lang in server!.language"
                  :key="lang"
                  class="tag tag-secondary"
                >
                  {{ lang }}
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 内容标签页 -->
        <div class="card p-6">
          <div class="flex border-b border-gray-200 mb-6">
            <button 
              @click="activeTab = 'url'" 
              :class="[
                'py-2 px-4 font-medium mr-4 focus:outline-none',
                activeTab === 'url' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-500 hover:text-gray-700'
              ]"
            >
              服务器内容
            </button>
            <button 
              v-if="server!.github"
              @click="activeTab = 'readme'"
              :class="[
                'py-2 px-4 font-medium mr-4 focus:outline-none',
                activeTab === 'readme' ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-500 hover:text-gray-700'
              ]"
            >
              README
            </button>
          </div>

          <!-- URL内容标签页 -->
          <div v-if="activeTab === 'url' && server!.url" class="iframe-container">
            <iframe
              :src="server!.url"
              class="w-full h-[600px] border-0 rounded"
              sandbox="allow-same-origin allow-scripts"
              title="服务器内容"
            ></iframe>
          </div>
          <div v-else-if="activeTab === 'url' && !server!.url" class="text-center py-8">
            <p class="text-gray-600">未提供服务器URL</p>
          </div>

          <!-- README标签页 -->
          <div v-if="activeTab === 'readme'">
            <!-- 加载中 -->
            <div v-if="readmeLoading" class="py-8 text-center">
              <div class="spinner mx-auto mb-4"></div>
              <p class="text-gray-600">正在加载README内容...</p>
            </div>
            
            <!-- 错误提示 -->
            <div v-else-if="readmeError" class="bg-red-50 border-l-4 border-red-400 p-4">
              <p class="text-red-700">{{ readmeError }}</p>
              <p class="mt-2">
                <a :href="server!.github" target="_blank" class="text-blue-600 hover:text-blue-800 hover:underline">
                  在GitHub上查看项目
                </a>
              </p>
            </div>
            
            <!-- 嵌入GitHub README -->
            <div v-else-if="readmeContent" class="readme-frame-container">
              <iframe 
                v-if="server!.github"
                :src="`https://githubmd.glitch.me/${server!.github.replace('https://github.com/', '')}`"
                class="w-full h-[600px] border-0 rounded"
                title="GitHub README"
              ></iframe>
            </div>
            
            <!-- 备用方案：简单显示README内容 -->
            <div v-else-if="readmeContent" class="overflow-auto max-h-[600px] p-4 bg-gray-50 rounded">
              <pre class="whitespace-pre-wrap">{{ readmeContent }}</pre>
            </div>
            
            <!-- 没有README -->
            <div v-else class="py-8 text-center">
              <p class="text-gray-600">无法获取README内容</p>
              <p class="mt-2">
                <a :href="server!.github" target="_blank" class="text-blue-600 hover:text-blue-800 hover:underline">
                  在GitHub上查看项目
                </a>
              </p>
            </div>
          </div>
        </div>

        <!-- 示例代码 -->
        <div class="card p-6">
          <h2 class="text-xl font-bold text-gray-900 mb-4">使用示例</h2>
          <div class="bg-gray-800 rounded-lg p-4 overflow-x-auto">
            <pre class="text-gray-100 text-sm"><code>import { useMCPServer } from 'mcp-client';

// 初始化服务器连接
const server = useMCPServer('{{ server!.id }}');

// 使用服务器功能
const result = await server.connect();
console.log(result);</code></pre>
          </div>
        </div>

        <!-- 相关服务器 -->
        <div v-if="server!.tags.length > 0" class="card p-6">
          <h2 class="text-xl font-bold text-gray-900 mb-4">相关服务器</h2>
          
          <div class="server-grid">
            <div
              v-for="relatedServer in serverStore.servers.filter(s => 
                s.id !== server!.id && 
                s.tags.some(tag => server!.tags.includes(tag))
              ).slice(0, 3)"
              :key="relatedServer.id"
              class="bg-gray-50 rounded-lg p-4 cursor-pointer hover:bg-gray-100 transition-colors duration-200"
              @click="router.push({ name: 'server-detail', params: { id: relatedServer.id } })"
            >
              <div class="flex items-center justify-between mb-2">
                <h3 class="font-medium text-gray-900">{{ relatedServer.name }}</h3>
                <span
                  :class="[
                    'tag',
                    relatedServer.type === 'official' ? 'tag-success' : 'tag-primary'
                  ]"
                >
                  {{ relatedServer.type === 'official' ? '官方' : '社区' }}
                </span>
              </div>
              <p class="text-gray-600 text-sm line-clamp-2">{{ relatedServer.description }}</p>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-8 mt-12">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex flex-col md:flex-row justify-between items-center">
          <div class="mb-4 md:mb-0">
            <h2 class="text-xl font-bold">MCP Server 导航</h2>
            <p class="text-gray-400">Model Context Protocol 服务器资源集合</p>
          </div>
          <div class="flex space-x-4">
            <a href="https://mcp.so" target="_blank" class="text-gray-300 hover:text-white">
              官方网站
            </a>
            <a href="https://github.com" target="_blank" class="text-gray-300 hover:text-white">
              GitHub
            </a>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<style scoped>
.page-container {
  max-width: 1024px;
  margin: 0 auto;
  padding: 1.5rem;
}

.card {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

.tag {
  display: inline-flex;
  align-items: center;
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
}

.tag-primary {
  background-color: #e1effe;
  color: #1e40af;
}

.tag-secondary {
  background-color: #f3f4f6;
  color: #4b5563;
}

.tag-success {
  background-color: #dcfce7;
  color: #166534;
}

.server-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.spinner {
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 3px solid #3498db;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.iframe-container {
  position: relative;
  width: 100%;
  overflow: hidden;
  border-radius: 0.5rem;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
}
</style> 